import React, { useState, useEffect } from "react";
import {
  PlusOutlined,
  DeleteOutlined
} from "@ant-design/icons";
import type { SizeType } from "antd/es/config-provider/SizeContext";
import { Button, DatePicker, Input, Radio, Switch, Table,Modal ,Form} from "antd";
import type { RadioChangeEvent } from "antd";
import { notification } from "antd";
import "./index.scss";
import type { ColumnsType } from "antd/es/table";
import * as service from "../../../../api/cgg/users";
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

const CusMent = () => {
  const { RangePicker } = DatePicker;
  const { Search } = Input;

  function onOk(value: any) {
    console.log("onOk: ", value);
  }
  const [size, setSize] = useState<SizeType>("small");
  const onChange = (e: RadioChangeEvent) => {
    setSize(e.target.value);
  };
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState([]);
  const [defaultChecked, setdefaultChecked] = useState(Boolean);
  useEffect(() => {
    var userslist = async () => {
      var res = await service.findAllUser({ page: 1, limit: 100 });
      console.log(res.data.data);
      res.data.data.records.forEach((item: any, index: any) => {
        item.key = index;
        if (item.userState === 0) {
          setdefaultChecked(false);
        } else if (item.userState === 1) {
          setdefaultChecked(true);
        }
      });
      setData(res.data.data.records);
      console.log(res.data.data.records[0].userState);
    };
    userslist();
  }, []);

  var handleDef = (defaultChecked: any,userState: any) => {
      setdefaultChecked(!defaultChecked)

  notification.success({ message: "更新状态成功" });
  console.log(userState);
  };
  var flag = async (userId: any) => {
    console.log(userId);

    var res = await service.deleteUser({ userId});
    if (res.data.code == 200) {
      var newData = JSON.parse(JSON.stringify(data));
      var i: any = newData.findIndex(
        (item: any) => item.userId == userId
      );
      if (i != -1) {
        newData.splice(i, 1);
        setData(newData);
      }
      notification.success({ message: "删除成功" });
    } else {
      notification.error({ message: "删除失败" });
    }
  };
  const columns: ColumnsType<DataType> = [
    {
      title: "操作",
      dataIndex: "name",
      render: (_: any, record: any) => (
        <DeleteOutlined
          onClick={() => flag(record.userId)}
          style={{ color: "red", fontSize: "25px" }}
        />
      ),
    },
    {
      title: "客户名称",
      dataIndex: "userName",
    },
    {
      title: "统一信用代码",
      dataIndex: "userCode",
    },
    {
      title: "状态",
      dataIndex: "userState",
      render: (_: any, record: any) => {
        if (record.userState === 0) {
          return (
            <Switch
              onClick={() => handleDef(defaultChecked, record.userState)}
              defaultChecked={false}
            />
          );
        } else if (record.userState === 1) {
          return (
            <Switch
              onClick={() => handleDef(defaultChecked, record.userState)}
              defaultChecked={true}
            />
          );
        }
      },
    },
    {
      title: "简称",
      dataIndex: "userShortname",
    },
    {
      title: "代号",
      dataIndex: "userCodename",
    },
    {
      title: "编码",
      dataIndex: "userCodename",
    },
    {
      title: "区域",
      dataIndex: "userAddtime",
    },

    {
      title: "添加日期",
      dataIndex: "userAddtime",
    },
  ];

  var handleSerch = async (value: any) => {
    var res = await service.findAllUserByUserName({
      page: 1,
      limit: 10,
      userName: value,
    });
    console.log(res);
    res.data.data.records.forEach((item: any, index: any) => {
      item.key = index;
    });
    setData(res.data.data.records);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 点击已关注是触发
  var findState=async()=>{
    var res = await service.findAllUserByState({page:3,limit:3,state:1})
    console.log(res.data.data);
    res.data.data.records.forEach((item:any,index:number)=>{
          item.key=index
    })
    setdefaultChecked(true)
    setData(res.data.data.records)
  }
  // 点击未关注时触发
  var findStateOff=async()=>{
    var res = await service.findAllUserByState({page:2,limit:3,state:0})
    console.log(res.data.data);
    res.data.data.records.forEach((item:any,index:number)=>{
          item.key=index
    })
    setdefaultChecked(false)
    setData(res.data.data.records)
  }
  var findAll = async () => {
    var res = await service.findAllUserByUserName({ page: 1, limit: 100});
    console.log(res.data.data);
    res.data.data.records.forEach((item: any, index: any) => {
      item.key = index;
      if (item.userState === 0) {
        setdefaultChecked(false);
      } else if (item.userState === 1) {
        setdefaultChecked(true);
      }
    });
    setData(res.data.data.records);
  };



  const [open, setOpen] = useState(false);
  // function onOk(value: any) {
  //   console.log("onOk: ", value);
  // }
  const onFinish = async (values: any) => {
    console.log("Success:", values);
    var res = await service.addUser(values);
    console.log(res);
    if (res.data.code == 200) {
      notification.success({ message: res.data.msg });
      let newData = JSON.parse(JSON.stringify(data))
      newData.push(values)
      newData.forEach((item: any, index: any) => {
        item.key = index;
      });
      setData(newData)
    }

    setOpen(false);
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div>
      <div className="head">
        <Button onClick={() => setOpen(true)} type="default" icon={<PlusOutlined />}>
          增加客户
        </Button>

        <div className="right">
          <Radio.Group className="radio_list" value={size} onChange={onChange}>
            <Radio.Button onClick={()=>findAll()} value="small">全部</Radio.Button>
            <Radio.Button onClick={()=>findState()} value="middle">启用</Radio.Button>
            <Radio.Button onClick={()=>findStateOff()} value="large">禁用</Radio.Button>
          </Radio.Group>
          <Search
            style={{ width: 220 }}
            placeholder="请输入产品相关编码"
            enterButton="搜索"
            onSearch={(value) => handleSerch(value)}
          />
        </div>
      </div>
      <Table columns={columns} dataSource={data} rowSelection={rowSelection} />
      <Modal title="新增产品" footer={null} open={open} width={1000}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="客户名称"
            name="userName"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="统一信用代码"
            name="userCode"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="状态"
            name="userState"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="简称"
            name="userShortname"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="代号"
            name="userCodename"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="编码"
            name="userCodename"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="区域"
            name="userAere"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="添加日期"
            name="userAddtime"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" onClick={() => setOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              新增
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CusMent;
